package com.probiz.estoresa.system.web.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.model.system.AppMenu;
import com.probiz.estore.common.model.system.AppResource;
import com.probiz.estore.common.model.system.AppRole;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.system.service.AppMenuManager;
import com.probiz.estore.system.service.AppResourceManager;
import com.probiz.estore.system.service.AppRoleManager;

public class AppRoleController extends GenericStoreAdminController<AppRole> {
    private AppRoleManager appRoleManager = null;
    private AppResourceManager appResourceManager = null;
    private AppMenuManager appMenuManager = null;
    
    /*spring-mvc.xml中配置值*/
    private Short belongTo = null;
    public void setBelongTo(Short belongTo) {
		this.belongTo = belongTo;
	}

	public void setAppRoleManager(AppRoleManager inMgr) {
        this.appRoleManager = inMgr;
    }

	public void setAppResourceManager(AppResourceManager appResourceManager) {
		this.appResourceManager = appResourceManager;
	}

	public void setAppMenuManager(AppMenuManager appMenuManager) {
		this.appMenuManager = appMenuManager;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(AppRole entity) {
		return entity.getAppRoleName();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = appRoleManager;
		this.getServletContext().setAttribute("DEFAULT_ADMIN_ROLE_NAME", Constants.DEFAULT_ADMIN_ROLE_NAME);
	}
	
	@Override
	protected Map<String,String> getSortMap(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "convert_gbk(roleName)");
		sortMap.put("2", "convert_gbk(roleDetail)");
		sortMap.put("3", "createTime");
		sortMap.put("4", "updateTime");
		return sortMap;
	}
	
	public ModelAndView search(HttpServletRequest request,
			HttpServletResponse response) {
		SearchCriteria sc = createSearchCriteria(request,new Object[]{this.belongTo});
		List results = searchByCriteria(sc);
		request.setAttribute("requestURI", request.getRequestURI());
		return getModelAndView(listView, listModelName, results);
	}
	
	public ModelAndView save(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		
		// 取得Form对应的Model
		AppRole appRole = formBackingObject(request);
		BindException errors = null;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, appRole);
			errors = new BindException(binder.getBindingResult());
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		boolean isNew = (appRole.getVersion() == null);
		
		boolean isDefaultRole = Constants.DEFAULT_ADMIN_ROLE_NAME.equals(appRole.getRoleName());

		// -----------------------------------------------------
		// do save operation - for AppRole
		// -----------------------------------------------------
		if (appRole.getRoleId() == null) {
			boolean isRoleNameExist = appRoleManager.getIsRoleNameExist(appRole.getRoleName());
			if (isRoleNameExist) {
				Object[] params = { appRole.getRoleName() };
				errors.rejectValue("roleName", "appRole.roleName.exist", params, "the role name has exist!");
				data.put("message", this.getMessage("appRole.roleName.exist",params));
				data.put("error", true);
				return getModelAndAjaxJsonView(data);
			}
			// 新增的全部都不是系统默认的
			appRole.setIsSystem(Short.valueOf("0"));
			appRole.setBelongTo(this.belongTo);
			
			//新增时，封装好层次路径
			if(appRole.getParentId()!=null){
				AppRole parent = appRoleManager.loadById(appRole.getParentId());
				appRole.setRolePath((parent.getRolePath()==null?"":parent.getRolePath()) + parent.getRoleId()+".");
			}
		}
		if(!isDefaultRole){
			//appRole.getAppResourceRoles().clear();
			String[] resourceIds = request.getParameterValues("ckResourceId");
			// 其他resource
			if (resourceIds != null) {
				for (int i = 0; i < resourceIds.length; i++) {
					AppResource appResource = appResourceManager.getById(new Integer(resourceIds[i]));
					appRole.addResourceTemp(appResource);
					
				}
			}
			String[] menuIds = request.getParameterValues("ckMenuId");
			// 其他menu
			if (menuIds != null) {
				for (int i = 0; i < menuIds.length; i++) {
					AppMenu appMenu = appMenuManager.getById(new Integer(menuIds[i]));
					appRole.addMenuTemp(appMenu);
				}
			}
		}
		
		appRoleManager.save(appRole);
		
		String key = (isNew) ? "appRole.added" : "appRole.updated";
		data.put("message", this.getMessage(key, new Object[] { appRole.getRoleName() }));
		data.put("error", false);
		data.put("appRoleId", appRole.getRoleId());
		data.put("isDeleteable", appRole.getIsSystem().equals(Constants.FLAG_FALSE));
		return getModelAndAjaxJsonView(data);
	}
	
	@Override
	protected void onShowForm(HttpServletRequest request, ModelAndView mv){
		List<AppMenu> allMenus = appMenuManager.findTopMenus(belongTo,Constants.SECURITY_TYPE_MENU);
		List<AppMenu> allRess = appMenuManager.findTopMenus(belongTo,Constants.SECURITY_TYPE_RESOURCE);

		request.setAttribute("allMenus", allMenus);
		request.setAttribute("allRess", allRess);

		request.setAttribute("requestURI", request.getRequestURI());
		
//		GrantedAuthority[] recipents = SecurityContextHolder.getContext() .getAuthentication().getAuthorities();
//		for(GrantedAuthority ga:recipents)
//			System.out.println(ga.getAuthority());
	}

	@Override
	protected void preSave(HttpServletRequest request, AppRole entity, BindException errors) {
		
	}
	
}
